package io.ede.modules.ede.controller;

import java.io.*;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.ede.common.exception.RRException;
import io.ede.common.validator.ValidatorUtils;
import io.ede.modules.ede.service.ProjectService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.ede.modules.ede.entity.GroupEntity;
import io.ede.modules.ede.service.GroupService;
import io.ede.common.utils.PageUtils;
import io.ede.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-08-27 13:28:08
 */
@RestController
@RequestMapping("ede/group")
public class GroupController {
    @Autowired
    private GroupService groupService;
    @Autowired
    private ProjectService projectService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("ede:group:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = groupService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("ede:group:info")
    public R info(@PathVariable("id") Integer id){
        GroupEntity group = groupService.getById(id);

        return R.ok().put("group", group);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("ede:group:save")
    public R save(@RequestBody GroupEntity group){
        groupService.save(group);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("ede:group:update")
    public R update(@RequestBody GroupEntity group){
        ValidatorUtils.validateEntity(group);
        groupService.updateById(group);
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("ede:group:delete")
    public R delete(@RequestBody Integer[] ids){
        groupService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 获取动作组代码
     */
    @RequestMapping("/oneGroup")
    public R oneAction(@RequestParam Map<String, Object> params) throws Exception{
        Map<String, Object> map = new HashMap<>();
        map.put("project_id",params.get("id"));
        map.put("name",params.get("actionname"));
        List<GroupEntity> groupEntityList = (List<GroupEntity>)groupService.listByMap(map);
        if(groupEntityList!=null&&groupEntityList.size()>0){
            GroupEntity group = groupEntityList.get(0);
            return R.ok().put("group",group);
        }
        return R.error();
    }

    /**
     * 添加动作组代码
     */
    @RequestMapping("/addGroup")
    public R addGroup(@RequestParam Map<String, Object> params){
        groupService.addGroup(params);
        return R.ok();
    }

    /**
     * 删除动作组
     * @param params
     * @return
     */
    @RequestMapping("/delGroup")
    public R delGroup(@RequestParam Map<String, Object> params){
        groupService.delGroup(params);
        return R.ok();
    }

    /**
     * 添加无人机
     * @param params
     * @return
     */
    @RequestMapping("/addFlight")
    public R addFlight(@RequestParam Map<String, Object> params){
        groupService.addFlight(params);
        return R.ok();
    }

    /**
     * 查询无人机
     * @param params
     * @return
     */
    @RequestMapping("/getFlight")
    public R getFlight(@RequestParam Map<String, Object> params){
        Map<String,String> result = groupService.getFlight(params);
        return R.ok().put("result",result);
    }

    /**
     * 导出动作组
     * @return
     */
    @RequestMapping("/expGroup")
    public void expGroup(String projectId,String name,HttpServletResponse res){
        //查询动作组
        Map<String,Object> map = new HashMap<>();
        map.put("project_id",projectId);
        map.put("name",name);
        List<GroupEntity> groupList = (List<GroupEntity>)groupService.listByMap(map);

        if(groupList!=null&&groupList.size()>0){
            GroupEntity group = groupList.get(0);
            String xmlContent = group.getXml();
            //下载文件
            OutputStream os = null;
            try {
                res.setContentType("application/octet-stream");
                res.setHeader("Content-Disposition", "attachment;filename=" + new String((group.getName() + ".xml").getBytes("gb2312"), "ISO8859-1"));
                os = res.getOutputStream();
                byte[] b = xmlContent.getBytes("utf-8");
                os.write(b);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) {
                        os.flush();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导入动作组
     */
    @RequestMapping("/impGroup")
    public String importGroup(@RequestParam("file") MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (!".xml".equals(suffix)) {
            throw new RRException("文件格式不正确，只能是xml");
        }

        String xml = convertStreamToString(file);

        //return R.ok().put("xml",xml);
        return xml;

    }

    /**
     * 获取文件内容
     * @param file
     * @return
     */
    public String convertStreamToString(MultipartFile file){
        StringBuilder sb = new StringBuilder();
        try (InputStream inputStream = file.getInputStream()) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "/n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }


}
